package org.turnlink.sclm.web;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.turnlink.sclm.model.AccountSession;
import org.turnlink.sclm.service.SessionManager;

@Controller
@RequestMapping("/auth/{format}")
public class SessionServiceController extends AbstractServiceController {

	@Autowired
	private SessionManager sessionManager;
	
	@RequestMapping(value = "/getSessionToken/{userName}/{password}", method = RequestMethod.GET)
	public ModelAndView update(@PathVariable("format") String format,
			@PathVariable("userName") String userName,
			@PathVariable("password") String password, HttpServletResponse response) throws IOException {
		
		AccountSession session = sessionManager.createAccountSession(userName, password);
		
		if (session == null) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			return null;
		}

		return new ModelAndView(getViewName(format), "token", session.getToken());
	}
}
